<?php
/**
 *  Create On 2014-12-03
 *  Author yiwei
 *  QQ:1006629314
 **/
class CourseController extends Controller{
	private $datelist;
	private $colorlist;
	private $colorCount;
	public function __construct() {
		parent::__construct ();
		$this->view->web_host = $this->getRequest ()->hostUrl;
		$this->view->web_app_url = $this->getRequest ()->hostUrl . "/clientapi.php";
		
		
		$this->datelist['0'] = array("title"=>'本周',"date"=>strtotime('-1 week'));
		$this->datelist['1'] = array("title"=>'一周前',"date"=>strtotime('-2 week'));
		$this->datelist['2'] = array("title"=>'半月前',"date"=>strtotime('-1 month'));
		$this->datelist['3'] = array("title"=>'一月前',"date"=>strtotime('-6 month'));
		$this->datelist['4'] = array("title"=>'半年前',"date"=>0);
		
		$this->colorlist['0'] = array('R'=>82,'G'=>207,'B'=>188);
		$this->colorlist['1'] = array('R'=>255,'G'=>155,'B'=>89);
		$this->colorlist['2'] = array('R'=>208,'G'=>228,'B'=>143);
		$this->colorlist['3'] = array('R'=>65,'G'=>155,'B'=>252);
		$this->colorlist['4'] = array('R'=>250,'G'=>120,'B'=>134);
		$this->colorlist['5'] = array('R'=>244,'G'=>168,'B'=>194);
		$this->colorlist['6'] = array('R'=>255,'G'=>213,'B'=>65);
		$this->colorlist['7'] = array('R'=>191,'G'=>148,'B'=>132);
		$this->colorlist['8'] = array('R'=>175,'G'=>146,'B'=>215);
		$this->colorCount = 8;
	}
	
	public function getTeaCourseCal(){
		$userinfo = $this->getData ( 'userinfo' );
		$user_id = $userinfo ['id'];
		//$user_id = 50003;
		$year = $this->getRequest()->get('year')?$this->getRequest()->get('year'):date('Y');
		$month = $this->getRequest()->get('month');
		$weekoffset = $this->getRequest()->get('week')?$this->getRequest()->get('week'):0;
		if($month){
			$nowday = strtotime($year.'-'.$month.'-1');
			$firstday = strtotime('Sunday',$nowday);
			$weekoffset = floor(($firstday - time())/604800);
			$weekstr = '0 week';
		}else{
			$nowday = time();
			if($weekoffset>0){
				$weekstr = '+'.$weekoffset.' week';
			}else{
				$weekstr = $weekoffset.' week';
			}
		}
		$sunday = strtotime('Sunday',$nowday);
		$monday = strtotime('-6 day',$sunday);
		//var_dump(date('Y-m-d',$monday));
		
		$daylist = array(7);
		$start_timestamp = strtotime($weekstr,$monday);
		for($i=0;$i<7;$i++){
			$daylist[$i] = date('Y-m-d',strtotime('+'.$i.' day',$start_timestamp));
		}
		$week = date('N',$start_timestamp);
		$start_date = date('Y-m-d',$start_timestamp);
		$end_date = date('Y-m-d',strtotime('+1 week',$start_timestamp));
		
		$period = new period();
		//获取班级列表并翻转键值
		$list_class = $period->getClassList($user_id);
		if($list_class){
			foreach ($list_class as $key=>$val){
				$list_class[$key] = $list_class[$key]['class_id'];
			}
			$class_list = array_flip($list_class);
		}
		
		$list = $period->searchTeaPeriod(0,0,$user_id, 0, $start_date, $end_date);
		if($list && count($list)<>0){
			$totalCount = count($list);
			for($i=0;$i<$totalCount;$i++){
				$list[$i]['studentName'] = $this->getStudentName($list[$i]['classId']);
				$list[$i]['start_time'] = $list[$i]['date'].' '.$list[$i]['start_time'];
				$list[$i]['end_time'] = $list[$i]['date'].' '.$list[$i]['end_time'];
				$list[$i]['section'] .= '/'. $list[$i]['section_amount'];
				if ($list[$i]['videoId']){
					$list[$i]['videoStatue'] = 3;//有视频已上传
				}else{
					$list[$i]['videoStatue'] = 1;//无视频
				}
				if( $list[$i]['homeworkId']){
					switch($list[$i]['publish_type']){
						case '0':$list[$i]['homeworkStatue'] = 3;break;//暂不发布
						case '1':$list[$i]['homeworkStatue'] = 4;break;//定时发布
						//case '2':										//立即发布
						case '3':$list[$i]['homeworkStatue'] = 5;break;//已发布
						default:$list[$i]['homeworkStatue'] = 1;
					}
				}else{
					$list[$i]['homeworkStatue'] = 1;
				}
				if($list[$i]['noteId']){
					$list[$i]['noteStatue'] = 2;
				}else{
					$list[$i]['noteStatue'] = 1;
				}
				if($list[$i]['prepareId']){
					$list[$i]['prepareStatue'] = 2;
				}else{
					$list[$i]['prepareStatue'] = 1;
				}
				$list[$i]['R'] = $this->colorlist[$class_list[$list[$i]['classId']]%$this->colorCount]['R'];
				$list[$i]['G'] = $this->colorlist[$class_list[$list[$i]['classId']]%$this->colorCount]['G'];
				$list[$i]['B'] = $this->colorlist[$class_list[$list[$i]['classId']]%$this->colorCount]['B'];
			}
			$data = array("list"=>$list,"totalCount"=>$totalCount,"year"=>$year,
					"week"=>$week,"weekoffset"=>$weekoffset,"day"=>$daylist,"timeStamp"=>time());
			$this->view->setData ( $data );
			$this->view->setState ( "1" );
			$this->view->setMsg ( "获取成功" );
		}else{
			$data = array("list"=>(object)null,"totalCount"=>0,"year"=>$year,
					"week"=>$week,"weekoffset"=>$weekoffset,"day"=>$daylist,"timeStamp"=>time());
			$this->view->setData ( $data );
			$this->view->setState ( "0" );
			$this->view->setMsg ( "还不知道今天的安排哟~" );
		}
		$this->view->display ( "json" );
	}
	

	
	public function getStuCourseCal(){
		$userinfo = $this->getData ( 'userinfo' );
		$user_id = $userinfo ['id'];
		$year = $this->getRequest()->get('year');
		$month = $this->getRequest()->get('month');
		//$user_id = 49;
		if($year&&$month){
			$start_timestamp = strtotime($year.'-'.$month.'-1 00:00:00');
			$start_date = date('Y-m-d',$start_timestamp);
			$end_date = date('Y-m-d',strtotime('+1 month',$start_timestamp));
			$period = new period();
			$list = $period->searchStuPeriod(0,0,$user_id,0,$start_date, $end_date);
			if($list){
				$totalCount = $list?count($list):0;
				for($i=0;$i<$totalCount;$i++){
					$list[$i]['start_time'] = $list[$i]['date'].' '.$list[$i]['start_time'];
					$list[$i]['end_time'] = $list[$i]['date'].' '.$list[$i]['end_time'];
					$list[$i]['section'] .= '/'. $list[$i]['section_amount'];
					if($list[$i]['video_id']){
						if($this->hasViewedVideo($user_id, $list[$i]['video_id'])){
							$list[$i]['videoStatue'] = 3;//有视频已观看
						}else{
							$list[$i]['videoStatue'] = 2;//有视频未观看
						}
					}else{
						$list[$i]['videoStatue'] = 1;//无视频
					}
					if($list[$i]['homework_id']){				
						//有作业，检查是否完成
						$list[$i]['homeworkState'] =$this->getItemFeedback($list[$i]["homework_id"],$user_id);
						$list[$i]["needUploadImage"]=$this->needUploadImage($list[$i]["homework_id"], $user_id);
					}else{
						$list[$i]['homeworkState'] =2;
						$list[$i]["needUploadImage"]=2;
						$list[$i]['homeworkStatue'] = 1;//无作业
					}
					$list[$i]['R'] = $this->colorlist[$list[$i]['subject_id']%$this->colorCount]['R'];
					$list[$i]['G'] = $this->colorlist[$list[$i]['subject_id']%$this->colorCount]['G'];
					$list[$i]['B'] = $this->colorlist[$list[$i]['subject_id']%$this->colorCount]['B'];
				}				
				$data = array("list"=>$list,"totalCount"=>$totalCount);
				$this->view->setData ( $data );
				$this->view->setState ( "1" );
				$this->view->setMsg ( "获取成功" );
			}else{
				$this->view->setData ( null );
				$this->view->setState ( "0" );
				$this->view->setMsg ( "暂无数据" );
			}
		}else{
			$this->view->setData ( null );
			$this->view->setState ( "0" );
			$this->view->setMsg ( "参数错误" );
		}
		$this->view->display ( "json" );
	}
	
	public function getTeaCourseList(){
		$userinfo = $this->getData ( 'userinfo' );
		$user_id = $userinfo ['id'];
		//$user_id = 3;
		$type = $this->getRequest()->get('type');//1-视频2-作业3-笔记4-备课
		$start_date = $this->getRequest()->get('start_date');
		$end_date = $this->getRequest()->get('end_date');
		$classId = $this->getRequest()->get('classId');
		$classCode = $this->getRequest()->get('classCode');
		$course = urldecode($this->getRequest()->get('course'));
		$stuId = $this->getRequest()->get('stuId');
		$order = $this->getRequest()->get('order');
		
		$PageSize = $this->getRequest()->get('PageSize')?$this->getRequest()->get('PageSize'):0;
		$ListNum = $this->getRequest()->get('ListNum')?$this->getRequest()->get('ListNum'):0;
		
		$TimeStamp = $this->getRequest()->get('TimeStamp');

// 		if($classCode){
// 			$class_student = new class_student();
// 			$result = $class_student->getClassIdByCode($classCode);
// 			if($result){
// 				$classId = $result['id'];			
// 			}else{
// 				$this->view->setStatus ( "1" );
// 				$this->view->setData ( (object)null );
// 				$this->view->setState ( "0" );
// 				$this->view->setMsg ( "班级不存在" );
// 				$this->view->display ( "json" );
// 				exit();
// 			}
// 		}
		
		$data = (object)null;
		$period = new period();
		//获取班级列表并翻转键值
		$list_class = $period->getClassList($user_id);
		foreach ($list_class as $key=>$val){
			$list_class[$key] = $list_class[$key]['class_id'];
		}
		$class_list = array_flip($list_class);
		
		if($type == 2){
			$list = array(3);
			$list[0] = $period->searchTeaPeriod(0,0,$user_id, $type, $start_date, $end_date, 0, $classCode,$course, $stuId,$order);
			$list[1] = $period->searchTeaPeriod(0,0,$user_id, $type, $start_date, $end_date, 1, $classCode,$course, $stuId,$order);
			$list[2] = $period->searchTeaPeriod($PageSize,$ListNum,$user_id, $type, $start_date, $end_date, 3, $classCode,$course, $stuId,$order);
			//var_dump($list);
			foreach ($list as $key=>$val){
				if($list[$key]){
					$totalCount = count($list[$key]);					
					for($i=0;$i<$totalCount;$i++){
						$list[$key][$i]['studentName'] = $this->getStudentName($list[$key][$i]['classId']);
						$list[$key][$i]['start_time'] = $list[$key][$i]['date'].' '.$list[$key][$i]['start_time'];
						$list[$key][$i]['end_time'] = $list[$key][$i]['date'].' '.$list[$key][$i]['end_time'];
						$list[$key][$i]['section'] .= '/'. $list[$key][$i]['section_amount'];
						$list[$key][$i]['R'] = $this->colorlist[$class_list[$list[$key][$i]['classId']]%$this->colorCount]['R'];
						$list[$key][$i]['G'] = $this->colorlist[$class_list[$list[$key][$i]['classId']]%$this->colorCount]['G'];
						$list[$key][$i]['B'] = $this->colorlist[$class_list[$list[$key][$i]['classId']]%$this->colorCount]['B'];
					}
				}else{
					$list[$key] = (object)null;
				}
			}
			$data = array("list"=>$list);
		}else{
			$list = $period->searchTeaPeriod($PageSize,$ListNum,$user_id, $type, $start_date, $end_date, -1, $classCode,$course, $stuId,$order);
			if($list){
				$totalCount = count($list);
				$titleCount = 0;
				for($i=0;$i<$totalCount;$i++){
					$list[$i]['studentName'] = $this->getStudentName($list[$i]['classId']);
					$list[$i]['start_time'] = $list[$i]['date'].' '.$list[$i]['start_time'];
					$list[$i]['end_time'] = $list[$i]['date'].' '.$list[$i]['end_time'];
					$list[$i]['section'] .= '/'. $list[$i]['section_amount'];
					$list[$i]['R'] = $this->colorlist[$class_list[$list[$i]['classId']]%$this->colorCount]['R'];
					$list[$i]['G'] = $this->colorlist[$class_list[$list[$i]['classId']]%$this->colorCount]['G'];
					$list[$i]['B'] = $this->colorlist[$class_list[$list[$i]['classId']]%$this->colorCount]['B'];
				}
				$data = array("list"=>$list,"totalCount"=>$totalCount);
			}
		}
		if(array_key_exists('list', $data) && count($data["list"])<>0){
			$this->view->setStatus ( "1" );
			$this->view->setData ( $data );
			$this->view->setState ( "1" );
			$this->view->setMsg ( "获取成功" );
		}else{
			$this->view->setData ( (object)null );
			$this->view->setState ( "0" );
			$this->view->setMsg ( "没有匹配的结果哟!" );
		}
		$this->view->display ( "json" );
	}
	
	public function getStuCourseList(){
		$userinfo = $this->getData ( 'userinfo' );
		$user_id = $userinfo ['id'];
 		//$user_id = 1009;
		$type = $this->getRequest()->get('type');
		$start_date = $this->getRequest()->get('start_date');
		$end_date = $this->getRequest()->get('end_date');
		$classId = $this->getRequest()->get('classId');
		$course = urldecode($this->getRequest()->get('course'));
		$teacherId = $this->getRequest()->get('teacherId');
		$order = $this->getRequest()->get('order');
		
		$GroupSize = $this->getRequest()->get('GroupSize')? $this->getRequest()->get('GroupSize'):1;
		$PageSize = $this->getRequest()->get('PageSize');
		$ListNum = $this->getRequest()->get('ListNum');
		
		$TimeStamp = $this->getRequest()->get('TimeStamp');
		
		$period = new period();
		$prelist = $period->searchStuPeriod($PageSize,$ListNum,$user_id,$type,$start_date,$end_date,$classId,$course,$teacherId,$order);
		if($prelist){
			$totalCount = $prelist?count($prelist):0;
			$list = array((int)($totalCount/$GroupSize)+1);
			$itemCount = 0;
			$groupCount = 0;
			$titleCount = 0;
			while ($itemCount<$totalCount){
				$num = (($totalCount-$itemCount)<$GroupSize)?($totalCount-$itemCount):$GroupSize;
				$dateLimit = $this->datelist[$titleCount];
				$innerlist = array();
				for($k = 0;$k<$num;$k++){
					//$listitem = array();
					if(strtotime($prelist[$itemCount+$k]['date'])<$dateLimit['date']){
						$titleCount++;
						break;
					}
					$listitem = $prelist[$itemCount+$k];
					$listitem['start_time'] = $listitem['date'].' '.$listitem['start_time'];
					$listitem['end_time'] = $listitem['date'].' '.$listitem['end_time'];
					$listitem['section'] .= '/'. $listitem['section_amount'];
					if(array_key_exists('video_id', $listitem)){
						if($this->hasViewedVideo($user_id, $listitem['video_id'])){
							$listitem['videoStatue'] = 3;//有视频已观看
						}else{
							$listitem['videoStatue'] = 2;//有视频未观看
						}
					}else{
						$listitem['videoStatue'] = 1;//无视频
					}
					if(array_key_exists('homework_id', $listitem)){
						//有作业，检查是否完成
						$listitem['homeworkState'] =$this->getItemFeedback($listitem["homework_id"],$user_id);
						$listitem["needUploadImage"]=$this->needUploadImage($listitem["homework_id"], $user_id);
					}else{
						$listitem['homeworkState'] =2;
						$listitem["needUploadImage"]=2;
						$listitem['homeworkStatue'] = 1;//无作业
					}
					$listitem['R'] = $this->colorlist[$listitem['subject_id']%$this->colorCount]['R'];
					$listitem['G'] = $this->colorlist[$listitem['subject_id']%$this->colorCount]['G'];
					$listitem['B'] = $this->colorlist[$listitem['subject_id']%$this->colorCount]['B'];
					$innerlist[$k] = $listitem;
				}
				if($k == 0){
					continue;
				}

				$list[$groupCount] = array("title"=>$dateLimit['title'],"list"=>$innerlist,"totalCount"=>$k);
				$groupCount++;
				$itemCount += $k;
			}
			//var_dump($list);
			$data = array("list"=>$list,"totalCount"=>$totalCount,"listNum"=>($ListNum+$totalCount),"timeStamp"=>time());
			$this->view->setData ( $data );
			$this->view->setState ( "1" );
			$this->view->setMsg ( "获取成功" );
		}else{
			$this->view->setData ( null );
			$this->view->setState ( "0" );
			$this->view->setMsg ( "没有更多了哟!" );
		}
		$this->view->display ( "json" );
	}
	
	/*
	 * 获取学生列表
	 */
	public function getStudentList(){
		$userinfo = $this->getData ( 'userinfo' );
		$user_id = $userinfo ['id'];
		
		//$user_id = 33;
		$period = new period();
		$result = $period->getStudentList($user_id);
		if($result){
			$this->view->setData ( $result );
			$this->view->setState ( "1" );
			$this->view->setMsg ( "获取成功" );
		}else{
			$this->view->setData ( null );
			$this->view->setState ( "0" );
			$this->view->setMsg ( "没有更多了哟!" );
		}
		$this->view->display ( "json" );
	}
	
	/*
	 * 获取课程列表
	 */
	public function getCourseList(){
		$userinfo = $this->getData ( 'userinfo' );
		$user_id = $userinfo ['id'];
		//$user_id = 49;
		$isStudent = $this->getRequest()->get('isStudent');
		$period = new period();
		if($isStudent){
			($course = $period->getCourseList(null,$user_id)) || ($course = null) ;
			$class_student = new class_student();
			($class = $class_student->getClassInfoByStudent($user_id)) || ($class = null);
			$knowledge = new knowledge();
			($subject = $knowledge->getSubList()) || ($subject = null);
			($teacher = $class_student->getTeacherInfoByStudent($user_id)) || ($teacher = null);
			$result = array("courseInfo"=>$course,"classInfo"=>$class,"teacherInfo"=>$teacher,"subjectInfo"=>$subject);
		}else{
			$result = $period->getCourseList($user_id);
		}
		if($result){
			$this->view->setData ( $result );
			$this->view->setState ( "1" );
			$this->view->setMsg ( "获取成功" );
		}else{
			$this->view->setData ( (object)null );
			$this->view->setState ( "0" );
			$this->view->setMsg ( "没有更多了哟!" );
		}	
		$this->view->display ( "json" );
	}
	
	
	//for test
	public function test(){
		$homework_id=1;
		$user_id=49;
		$video_id=1;
		echo "<br>题目反馈：".$this->getItemFeedback($homework_id,$user_id)."<br>";
		echo "<br>是否需要反馈：".$this->getNeedFeedback($homework_id)."<br>";
		echo "<br>学生端需要上传图片：".$this->needUploadImage($homework_id,$user_id)."<br>";
		echo "<br>是否观看过视频：".$this->hasViewedVideo($user_id, $video_id)."<br>";
	}
	//获取学生是否需要上传图片
	private function needUploadImage($homework_id,$user_id){
		if($this->getItemFeedback($homework_id,$user_id)){
			return 0;
		}else if($this->getNeedFeedback($homework_id)){
			if($this->getImageFeedback($homework_id,$user_id)){
				return 0;
			}else{
				return 1;
			}
		}
	}
	//获取作业是否需要反馈
	private function getNeedFeedback($homework_id){
		$homework=new homework();
		if($homeworkInfo=$homework->getHomeworkById($homework_id))
			return $homeworkInfo["need_feedback"];
		else 
			return 2;
	}
	//获取图片反馈
	private function getImageFeedback($homework_id,$user_id){
		$homework_feedback=new homework_feedback();
		$imageFeedbackResult=1;
		//获取图片反馈结果
		$imageFeedback=$homework_feedback->getHomeworkImageState($user_id, $homework_id);
		$imageFeedbackResult=$imageFeedback["imagefeedback"];
		return $imageFeedbackResult;
	}
	//获取题目反馈
	private function getItemFeedback($homework_id,$user_id){
		$itemFeedbackResult=1;
		$homework = new homework();
		$result = $homework->getHomeworkById($homework_id);
		if($result){
			$preliststr = $result['item_id_str'];
			$itemIdArray = explode('_', $preliststr);
			$teacher_id = $result['teacher_id'];
// 			var_dump($itemIdArray);
			$itemFeedback=new item_feedback();
			foreach($itemIdArray as $key=>$val){
				if(!$itemFeedback->getFeedback($user_id, $homework_id, $val))
					$itemFeedbackResult=0;
			}
		}else{
			$itemFeedbackResult=2;
		}
		
		return $itemFeedbackResult;
	}
	//获取一个班级的学生名称拼接字符串
	private function getStudentName($classId){
		$class_student = new class_student();
		$studentList = $class_student->getStudentNameByPeriod($classId);
		$studentName = '';
		if($studentList){
			foreach ($studentList as $val){
				$studentName .= $val['name'];
			}
		}
		return $studentName;
	}
	private function hasViewedVideo($user_id,$video_id){
		
		$log=new log();
		if($log->getLog($user_id, "Video", "Play", $log->resource_type["video"], $video_id))
		{
			return true;
		}else {
			return false;
		}
	}
	private function hasNotification($type,$videoId){
		return mt_rand(0,1);  
	}
}
